#include "bsp_beep.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/ledc.h"
static QueueHandle_t beep_queue = NULL;

void beep_set_duty(uint16_t duty)
{
    // Set duty to 50%
    ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_1, duty));
    // Update duty to apply the new value
    ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_1));
}


static void _beep_start()
{
    beep_set_duty(256/2);
}

static void _beep_stop()
{
    beep_set_duty(0);
}

static void _beep_output(uint8_t _beep_status)
{
    _beep_start();
	switch(_beep_status){
		case BEEP_BUTTON:
        case BEEP_START:
        case BEEP_STOP:
			vTaskDelay(50 / portTICK_PERIOD_MS);
			break;

		case BEEP_ERROR:
			vTaskDelay(500 / portTICK_PERIOD_MS);
			_beep_stop();
			vTaskDelay(500 / portTICK_PERIOD_MS);
			_beep_start();
			vTaskDelay(500 / portTICK_PERIOD_MS);
			break;
		case BEEP_WARN:
			vTaskDelay(100 / portTICK_PERIOD_MS);
			_beep_stop();
			vTaskDelay(100 / portTICK_PERIOD_MS);
			_beep_start();
			vTaskDelay(100 / portTICK_PERIOD_MS);
			break;
		default:
			break;
	}
    
    _beep_stop();
}

static uint8_t beep_status = 0;
void beep_output(uint8_t _beep_status)
{
    beep_status = _beep_status;
    xQueueSend(beep_queue, &beep_status, 0);
}

void task_beep(void* arg)
{
    uint32_t beep_value = 0;
    for(;;){
        xQueueReceive(beep_queue, &beep_value, portMAX_DELAY);
        if(beep_value < BEEP_MAX){
            _beep_output(beep_value);
        }
    }
}


/**
 * @brief 蜂鸣器初始化
*/
void beep_init()
{
     // Prepare and then apply the LEDC PWM timer configuration
    ledc_timer_config_t beep_timer = {
        .speed_mode       = LEDC_LOW_SPEED_MODE,
        .duty_resolution  = LEDC_TIMER_8_BIT,
        .timer_num        = LEDC_TIMER_1,
        .freq_hz          = 3000,  
        .clk_cfg          = LEDC_AUTO_CLK,
    };
    ESP_ERROR_CHECK(ledc_timer_config(&beep_timer));

    // Prepare and then apply the LEDC PWM channel configuration
    ledc_channel_config_t beep_channel1 = {
        .speed_mode     = LEDC_LOW_SPEED_MODE,
        .channel        = LEDC_CHANNEL_1,
        .timer_sel      = LEDC_TIMER_1,
        .intr_type      = LEDC_INTR_DISABLE,
        .gpio_num       = GPIO_BEEP_PORT,
        .duty           = 0, // Set duty to 0%
        .hpoint         = 0
    };
    ESP_ERROR_CHECK(ledc_channel_config(&beep_channel1));
    beep_queue = xQueueCreate(10, sizeof(uint32_t));//创建消息队列
    xTaskCreate(&task_beep, "task_beep", 1024, NULL, 9, NULL);
}



